import 'dart:io';
import 'dart:convert';

import 'package:camera/camera.dart';
import 'package:clean_app/asset/color.dart';
import 'package:clean_app/asset/modal.dart';
import 'package:clean_app/asset/storage.dart';
import 'package:clean_app/asset/textstyle.dart';
import 'package:clean_app/interface/mid_interface.dart';
import 'package:clean_app/outer/bounding_box_annotation/annotation_controller.dart';
import 'package:clean_app/outer/bounding_box_annotation/widgets/bounding_box_annotation.dart';
import 'package:clean_app/pages/vision/vision.dart';
import 'package:clean_app/provider/task_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:uuid/uuid.dart';

class ProcessImg extends StatefulWidget {
  final XFile file;

  List<String> levels;
  ProcessImg({super.key, required this.file, required this.levels});

  @override
  State<ProcessImg> createState() => _ProcessImgState();
}

class _ProcessImgState extends State<ProcessImg> {
  final AnnotationController annotationController = AnnotationController();

  Uint8List? imageBytes;
  double? aspectRatio;

  getByte() async {
    imageBytes = await widget.file.readAsBytes();
    final image = await decodeImageFromList(imageBytes!);
    aspectRatio = image.width / image.height;
    setState(() {});
  }

  Future<File> convertToImage(Uint8List imageByte) async {
    var tempDir = await getTemporaryDirectory();
    var file =
        await File('${tempDir.path}/image_${DateTime.now().millisecond}.jpg')
            .create();
    file.writeAsBytesSync(imageByte);
    return file;
  }

  confirmUpload() async {
    LoadingDialog.show(context);
    var res = await UploadApi().getPresignedUrl();
    var presignedUrl = res["data"]["url"];
    var compressedImage = await FlutterImageCompress.compressWithFile(
      widget.file.path,
      // minWidth: 1000,
      // minHeight: 1000,
      quality: 40,
    );
    // print(annotationController.offsetLists[0]);
    // return;
    var tmpFile = await convertToImage(compressedImage!);
    await UploadApi().uploadWithPresignedUrl(
      tmpFile.path,
      presignedUrl,
      (progress_1, progress_2) {},
    );
    var imgUrl = presignedUrl.split("?")[0];
    await TaskApi().postSubmissions({
      "submissions": [
        {
          "client_id": Uuid().v4(),
          "image_url": imgUrl,
          "task_context": widget.levels,
          "score": 0,
          "tags": [],
          "annotations": List.generate(
            annotationController.labelList.length,
            (idx) {
              var label = annotationController.labelList[idx];
              var offset = annotationController.offsetLists[idx];
              return {
                "type": "rectangle",
                "remark": label.remark,
                "bounding_box": [
                  offset[0].dx.toInt(),
                  offset[0].dy.toInt(),
                  offset[2].dx.toInt(),
                  offset[2].dy.toInt(),
                ],
                // "tags": [label.tag],
                // "score": label.score,
              };
            },
          ).toList(),
        }
      ],
    });
    LoadingDialog.dismiss(context);
    Toast.showInCenter(text: "上传完成", context: context);
    Navigator.of(context).pop();
    Navigator.of(context).pop();
  }

  // 保存草稿功能
  saveDraft() async {
    try {
      // 构造草稿数据
      final draftData = {
        "client_id": Uuid().v4(),
        "timestamp": DateTime.now().millisecondsSinceEpoch,
        "image_path": widget.file.path,
        "task_context": widget.levels,
        "score": 0,
        "tags": [],
        "annotations": List.generate(
          annotationController.labelList.length,
          (idx) {
            var label = annotationController.labelList[idx];
            var offset = annotationController.offsetLists[idx];
            return {
              "type": "rectangle",
              "remark": label.remark,
              "bounding_box": [
                offset[0].dx.toInt(),
                offset[0].dy.toInt(),
                offset[2].dx.toInt(),
                offset[2].dy.toInt(),
              ],
              "tags": [label.tag],
              "score": label.score,
            };
          },
        ).toList(),
      };

      // 获取现有的草稿列表
      String existingDraftsStr =
          await getStorage(key: "drafts", initData: "[]");
      List<dynamic> existingDrafts = json.decode(existingDraftsStr);

      // 添加新草稿
      existingDrafts.add(draftData);

      // 保存更新后的草稿列表
      await setStorage(key: "drafts", value: json.encode(existingDrafts));

      Toast.showInCenter(text: "草稿已保存", context: context);
      Navigator.of(context).pop(); // 关闭当前页面
      Navigator.of(context).pop(); // 返回上一页
    } catch (e) {
      Toast.showInCenter(text: "保存失败: $e", context: context);
    }
  }

  getPresetTag() async {
    var _p = Provider.of<PresetTagProvider>(context, listen: false);
    _p.getData();
  }

  @override
  void initState() {
    getByte();
    getPresetTag();
    super.initState();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          "上传图片",
          style: XSTextStyle(
            context: context,
            color: os_black,
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: [
          // TextButton(
          //   onLongPress: () {
          //     saveDraft(); // 调用保存草稿方法
          //   },
          //   onPressed: () {
          //     confirmUpload();
          //     return;
          //     showModal(
          //       context: context,
          //       title: "请确认",
          //       cont: "是否完成标注并提交上传？",
          //       confirmTxt: "完成并提交",
          //       cancelTxt: "保存草稿",
          //       cancel: () {
          //         saveDraft(); // 调用保存草稿方法
          //       },
          //       confirm: () {
          //         confirmUpload();
          //       },
          //     );
          //   },
          //   child: Text(
          //     "完成",
          //     style: XSTextStyle(
          //       context: context,
          //       color: os_color,
          //       fontSize: 16,
          //       fontWeight: FontWeight.bold,
          //     ),
          //   ),
          // ),
        ],
        leading: IconButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          icon: Icon(
            Icons.chevron_left,
            size: 28,
          ),
        ),
      ),
      body: ListView(
        physics: ClampingScrollPhysics(),
        children: [
          if (imageBytes != null && aspectRatio != null)
            // 使用AspectRatio保持图片比例
            AbsorbPointer(
              child: Container(
                margin: EdgeInsets.only(left: 15, right: 15),
                child: AspectRatio(
                  aspectRatio: aspectRatio!,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(10),
                    child: BoundingBoxAnnotation(
                      color: os_red,
                      strokeWidth: 8,
                      controller: annotationController,
                      imageBytes: imageBytes!,
                      imageWidth: (MediaQuery.of(context).size.width - 30),
                      imageHeight: (MediaQuery.of(context).size.width - 30) /
                          aspectRatio!,
                    ),
                  ),
                ),
              ),
            ),
          Container(height: 20),
          if (imageBytes != null && aspectRatio != null && imageBytes != null)
            Container(
              margin: EdgeInsets.only(left: 15, right: 15),
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor: WidgetStateProperty.all(os_color),
                  foregroundColor: WidgetStateProperty.all(os_white),
                  padding: WidgetStateProperty.all(
                    EdgeInsets.only(top: 15, bottom: 15),
                  ),
                ),
                onPressed: () {
                  confirmUpload();
                },
                child: Text(
                  "确认上传",
                  style: XSTextStyle(
                    context: context,
                    color: os_white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          if (imageBytes != null && aspectRatio != null && imageBytes != null)
            Container(
              margin: EdgeInsets.only(left: 15, right: 15, top: 15),
              child: ElevatedButton(
                style: ButtonStyle(
                  backgroundColor:
                      WidgetStateProperty.all(os_wonderful_color[3]),
                  padding: WidgetStateProperty.all(
                    EdgeInsets.only(top: 15, bottom: 15),
                  ),
                ),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => VisionTab(
                        imageFile: File(widget.file.path),
                      ),
                    ),
                  );
                },
                child: Text(
                  "问问AI",
                  style: XSTextStyle(
                    context: context,
                    color: os_white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          Container(height: 20),
        ],
      ),
    );
  }
}
